package com.seckill.controller;

import com.seckill.dto.Exposer;
import com.seckill.dto.SeckillExecution;
import com.seckill.dto.SeckillResult;
import com.seckill.entity.Seckill;
import com.seckill.exception.seckillException.RepeatKillException;
import com.seckill.exception.seckillException.SeckillCloseException;
import com.seckill.service.SeckillService;
import com.seckill.util.SeckillStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @Creation_time 2017/9/8
 * @Theme 秒杀controller层
 * @Autor Xiao Yiyun
 */

@Controller
@RequestMapping("/seckill") //url:/模块/资源/{id}/细分
public class SeckillController {

    @Autowired
    private SeckillService seckillService;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //查询所有秒杀对象--传入偏移量 使用GET方法
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public String list(Model model) {
        List<Seckill> list = seckillService.selectAllSeckill(0, 5);
        model.addAttribute("list", list);
        //list.jsp + model = ModeAndView
        return "list";
    }

    //根据Id查询秒杀信息
    @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET)
    @ResponseBody
    public String detail(@PathVariable("seckillId") Integer seckillId, Model model) {
        //如果id为NULL，转发给查询所有秒杀对象
        if (seckillId == null) {
            return "redirect:seckill/list";
        }
        //调用业务层返回查询业务结果
        Seckill seckill = seckillService.selectSeckillById(seckillId);
        //如果返回值为NULL,转发给查询所有秒杀对象
        if (seckill == null) {
            return "redirect:seckill/list";
        }
        model.addAttribute("seckill", seckill);
        return "detail";
    }

    //秒杀开启时输出秒杀接口地址，否则输出系统时间和秒杀时间
    @RequestMapping(value = "/{seckillId}/exposer",
                    method = RequestMethod.POST,
                    //解决中文乱码问题
                    produces = {"application/json;charset=UTF8"})
    //将返回值类型封装成json
    @ResponseBody
    public SeckillResult<Exposer> exposer(@PathVariable Integer seckillId) {
        SeckillResult<Exposer> result = null;
        try {
            Exposer exposer = seckillService.exportSeckillUrl(seckillId);
            result = new SeckillResult<Exposer>(true, exposer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new SeckillResult<Exposer>(false, e.getMessage());
        }
        return result;
    }

    //执行秒杀
    @RequestMapping(value = "/{seckillId}/{md5}/execution",
                    method = RequestMethod.POST,
                    produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Integer seckillId,
                                                   @PathVariable("md5") String md5,
                                                   @CookieValue(value = "userPhone", required = false) String userPhone) {
        SeckillResult<SeckillExecution> result = null;
        //验证cookie是否传入用户手机号 springmvc valid
        if (userPhone == null) {
            return new SeckillResult<SeckillExecution>(false, "未注册");
        }
        try {
            SeckillExecution seckillExecution = seckillService.executeSeckill(seckillId, userPhone, md5);
            result = new SeckillResult<SeckillExecution>(true, seckillExecution);
        } catch (RepeatKillException e) {
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStatusEnum.REPEAT_KILL);
            result = new SeckillResult<SeckillExecution>(true, seckillExecution);
        } catch (SeckillCloseException e) {
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStatusEnum.END);
            result = new SeckillResult<SeckillExecution>(true, seckillExecution);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStatusEnum.INNER_ERROR);
            result = new SeckillResult<SeckillExecution>(true, seckillExecution);
        }
        return result;
    }

    //获得当前服务器时间
    @RequestMapping(value = "/time/now", method = RequestMethod.GET)
    @ResponseBody
    public SeckillResult<Long> nowTime() {
        Date nowTime = new Date();
        return new SeckillResult<Long>(true, nowTime.getTime());
    }
}